import { useWebSocket } from "@vueuse/core";

export interface IWebSocketConfig {
  wsUrl: string;
  isHeartbeat?: boolean;
  isAutoReconnect?: boolean;
  immediate?: boolean;
  autoReconnect?: {
    retries?: number;
    delay?: number;
  };
  heartbeat?: {
    message?: string;
    interval?: number;
    pongTimeout?: number;
  };
  onFailedCall?: Function;
  onConnectedCall?: Function;
  onDisconnectedCall?: Function;
  onErrorCall?: Function;
  onMessageCall?: Function;
}

export const useWebSocketHook = (options?: IWebSocketConfig): any => {
  const {
    autoReconnect = {},
    isHeartbeat = false,
    isAutoReconnect = true,
    immediate = true,
    heartbeat = {},
    onConnectedCall,
    onDisconnectedCall,
    onErrorCall,
    onMessageCall,
    onFailedCall,
    wsUrl
  } = options ?? {};

  console.log(`wsUrl`, wsUrl);
  const { status, data, send, open, close, ws } = useWebSocket(wsUrl, {
    autoReconnect: isAutoReconnect
      ? {
          retries: 20, // 最大重试次数。
          delay: 2000, // 延迟
          onFailed() {
            console.log("*** Failed to connect WebSocket after 3 retries ***");
            onFailedCall && onFailedCall();
          },
          ...autoReconnect
        }
      : false,
    immediate: immediate,
    heartbeat: isHeartbeat
      ? {
          message: "ping",
          interval: 30 * 1000,
          pongTimeout: 30 * 1000,
          ...heartbeat
        }
      : false,
    onConnected(ws: WebSocket) {
      console.log("链接成功", ws);
      onConnectedCall && onConnectedCall(ws);
    },
    onDisconnected(ws: WebSocket, event: CloseEvent) {
      onDisconnectedCall && onDisconnectedCall(ws, event);
    },
    onError(ws: WebSocket, event: Event) {
      onErrorCall && onErrorCall(ws, event);
    },
    onMessage(ws: WebSocket, event: MessageEvent) {
      if (event.data == '{"type":"ping"}') {
        send('{"type":"pong"}');
        return;
      }
      onMessageCall && onMessageCall(ws, event);
    }
  });

  return {
    status,
    data,
    send,
    open,
    close,
    ws
  };
};
